using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos.DrugManagement;
using Work.Domain;
using Work.ErrorCode;

namespace WinFormsApp1.DrugManagement
{
    /// <summary>
    /// 药品出库窗体（用于药品出库模块）
    /// 功能：
    /// 1. 从库存中扣除药品（发药给患者）
    /// 2. 记录出库明细（关联处方、患者信息）
    /// 3. 更新药品库存数量
    /// 
    /// 注意：需要在Designer中添加控件，详见"前端窗体控件说明.md"
    /// </summary>
    public partial class DrugOutboundForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private List<DrugDto> _drugs;
        private DrugDto? _selectedDrug;

        private InspectionListDto? _inspectionInfo;
        
        // 隐藏的ID字段（不在界面显示，用于提交时使用）
        private int? _patientId;
        private int? _prescriptionItemId;
        private int? _appointmentId;
        private int? _drugId;

        public DrugOutboundForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _drugs = new List<DrugDto>();

            LoadAllDrugs();
        }

        /// <summary>
        /// 从检药单创建出库窗体
        /// </summary>
        public DrugOutboundForm(InspectionListDto inspectionInfo) : this()
        {
            _inspectionInfo = inspectionInfo;
            InitializeFromInspection();
        }

        /// <summary>
        /// 从检药单信息初始化出库窗体
        /// </summary>
        private void InitializeFromInspection()
        {
            if (_inspectionInfo == null) return;

            // 保存ID到私有变量（不在界面显示）
            _patientId = _inspectionInfo.PatientId;
            _prescriptionItemId = _inspectionInfo.PrescriptionItemId;
            _appointmentId = _inspectionInfo.AppointmentId;
            _drugId = _inspectionInfo.DrugId;

            // 界面只显示业务信息（患者信息）
            txtCardNumber.Text = _inspectionInfo.CardNumber ?? "";
            txtRegistrationNum.Text = _inspectionInfo.RegistrationNum ?? "";
            txtPatientName.Text = _inspectionInfo.PatientName ?? "";
            
            // 更新患者信息显示标签（如果存在）
            UpdatePatientInfoDisplay();

            // 如果有药品ID，尝试加载药品信息
            if (_inspectionInfo.DrugId.HasValue && _inspectionInfo.DrugId.Value > 0)
            {
                LoadDrugById(_inspectionInfo.DrugId.Value);
            }
            
            // 尝试从处方明细获取数量信息（如果有）
            LoadPrescriptionQuantity();
        }
        
        /// <summary>
        /// 从处方明细加载数量信息
        /// </summary>
        private async void LoadPrescriptionQuantity()
        {
            if (_inspectionInfo == null || _inspectionInfo.PrescriptionItemId <= 0) return;
            
            try
            {
                // 尝试从API获取处方明细信息
                var response = await _httpClient.GetAsync($"api/Prescription/GetByAppointment?appointmentId={_inspectionInfo.AppointmentId}");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<List<Work.API.Dtos.PrescriptionItemDto>>>(json, _jsonOptions);
                    if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                    {
                        var prescriptionItem = apiResult.Data.FirstOrDefault(pi => pi.PrescriptionItemId == _inspectionInfo.PrescriptionItemId);
                        if (prescriptionItem != null && prescriptionItem.Quantity > 0)
                        {
                            // 自动填充数量
                            if (txtQuantity != null)
                            {
                                txtQuantity.Text = prescriptionItem.Quantity.ToString();
                            }
                        }
                    }
                }
            }
            catch
            {
                // 静默处理错误，不影响主流程
            }
        }
        
        /// <summary>
        /// 更新患者信息显示（用于显示性别、年龄等）
        /// </summary>
        private void UpdatePatientInfoDisplay()
        {
            if (_inspectionInfo == null) return;
            
            // 如果存在患者信息显示标签，更新它们
            // 这些标签在Designer中定义
            var patientInfoText = "";
            if (!string.IsNullOrWhiteSpace(_inspectionInfo.PatientName))
            {
                patientInfoText = $"患者姓名：{_inspectionInfo.PatientName}";
            }
            if (_inspectionInfo.GenderText != null)
            {
                patientInfoText += $"  性别：{_inspectionInfo.GenderText}";
            }
            if (_inspectionInfo.Age.HasValue)
            {
                patientInfoText += $"  年龄：{_inspectionInfo.Age}";
            }
            
            // 如果存在lblPatientInfo标签，更新它
            var lblPatientInfo = this.Controls.Find("lblPatientInfo", true);
            if (lblPatientInfo.Length > 0 && lblPatientInfo[0] is Label label)
            {
                label.Text = patientInfoText;
            }
        }

        /// <summary>
        /// 根据药品ID加载药品信息
        /// </summary>
        private async void LoadDrugById(int drugId)
        {
            try
            {
                var response = await _httpClient.GetAsync($"api/Drug/GetDrugs");
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _drugs = apiResult.Data;
                    var drug = _drugs.Find(d => d.DrugId == drugId);
                    if (drug != null)
                    {
                        _selectedDrug = drug;
                        _drugId = drugId; // 保存药品ID
                        
                        // 更新药品信息显示（不显示ID）
                        UpdateDrugInfoDisplay(drug);
                        
                        // 设置下拉框选中该药品
                        RefreshDrugList();
                        if (cmbDrugName != null)
                        {
                            cmbDrugName.SelectedValue = drugId;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载药品信息失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 更新药品信息显示
        /// </summary>
        private void UpdateDrugInfoDisplay(DrugDto drug)
        {
            // 更新库存和单价显示（如果控件存在）
            if (txtCurrentInventory != null)
            {
                txtCurrentInventory.Text = drug.Inventory.ToString();
            }
            if (txtUnitPrice != null)
            {
                txtUnitPrice.Text = drug.SellingPrice.ToString("F2");
            }
            
            // 更新药品信息显示标签（如果存在）
            var drugInfoText = $"药品名称：{drug.DrugName}";
            if (!string.IsNullOrWhiteSpace(drug.Specification))
            {
                drugInfoText += $"  规格：{drug.Specification}";
            }
            drugInfoText += $"  当前库存：{drug.Inventory}  单价：{drug.SellingPrice:F2}元";
            
            if (lblDrugInfo != null)
            {
                lblDrugInfo.Text = drugInfoText;
            }
            
            // 更新总金额
            CalculateTotalAmount();
        }

        /// <summary>
        /// 加载所有药品
        /// </summary>
        private async void LoadAllDrugs()
        {
            try
            {
                var response = await _httpClient.GetAsync("api/Drug/GetDrugs?onlyEnabled=true");
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _drugs = apiResult.Data;
                    RefreshDrugList();
                    RefreshDrugListGridView();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载药品列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新药品列表表格
        /// </summary>
        private void RefreshDrugListGridView()
        {
            if (dgvDrugList != null)
            {
                // 添加DataError事件处理（如果还没有添加）
                dgvDrugList.DataError -= DgvDrugList_DataError;
                dgvDrugList.DataError += DgvDrugList_DataError;
                
                dgvDrugList.DataSource = null;
                dgvDrugList.DataSource = _drugs;
                SetDrugListColumnHeaders(dgvDrugList);
            }
        }

        /// <summary>
        /// 设置药品列表表格的中文列标题
        /// </summary>
        private void SetDrugListColumnHeaders(DataGridView dgv)
        {
            if (dgv.Columns.Count > 0)
            {
                var columnHeaders = new Dictionary<string, string>
                {
                    { "DrugId", "药品ID" },
                    { "DrugName", "药品名称" },
                    { "DrugType", "类型" },
                    { "CostName", "费用名称" },
                    { "DosageForm", "剂型" },
                    { "Specification", "规格" },
                    { "Inventory", "库存" },
                    { "InventoryUpperLimit", "库存上限" },
                    { "InventoryLowerLimit", "库存下限" },
                    { "PurchasePrice", "进价" },
                    { "SellingPrice", "售价" },
                    { "Efficacy", "功效" },
                    { "CreateTime", "创建时间" },
                    { "CreateBy", "创建人" },
                    { "UpdateTime", "更新时间" },
                    { "UpdateBy", "更新人" },
                    { "IsEnabled", "是否启用" }
                };

                // 先收集IsEnabled列的信息，避免在遍历时修改集合
                DataGridViewColumn? isEnabledColumn = null;
                int isEnabledColumnIndex = -1;

                // 第一遍遍历：设置列标题和格式，并找到IsEnabled列
                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    if (columnHeaders.ContainsKey(column.Name))
                    {
                        column.HeaderText = columnHeaders[column.Name];
                    }
                    
                    // 格式化进价和售价为两位小数
                    if (column.Name == "PurchasePrice" || column.Name == "SellingPrice")
                    {
                        column.DefaultCellStyle.Format = "F2";
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    }
                    
                    // 记录IsEnabled列的信息
                    if (column.Name == "IsEnabled")
                    {
                        isEnabledColumn = column;
                        isEnabledColumnIndex = column.Index;
                    }
                }

                // 第二遍：在循环外部处理IsEnabled列，避免修改集合时遍历
                if (isEnabledColumn != null && isEnabledColumnIndex >= 0)
                {
                    // 将列类型改为复选框
                    var checkBoxColumn = new DataGridViewCheckBoxColumn
                    {
                        Name = isEnabledColumn.Name,
                        HeaderText = isEnabledColumn.HeaderText,
                        DataPropertyName = isEnabledColumn.DataPropertyName,
                        ReadOnly = true,
                        Width = isEnabledColumn.Width
                    };
                    dgv.Columns.Remove(isEnabledColumn);
                    dgv.Columns.Insert(isEnabledColumnIndex, checkBoxColumn);
                    // 移除格式化事件处理器，因为复选框不需要格式化
                    dgv.CellFormatting -= DgvDrugList_IsEnabledFormatting;
                }
            }
        }

        /// <summary>
        /// 药品列表IsEnabled列的格式化事件
        /// </summary>
        private void DgvDrugList_IsEnabledFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (sender is DataGridView dgv && e.ColumnIndex >= 0 && e.ColumnIndex < dgv.Columns.Count && 
                    dgv.Columns[e.ColumnIndex].Name == "IsEnabled")
                {
                    // 处理bool类型
                    if (e.Value is bool boolValue)
                    {
                        e.Value = boolValue ? "是" : "否";
                        e.FormattingApplied = true;
                        return;
                    }
                    
                    // 处理可空bool类型
                    if (e.Value != null && e.Value is bool?)
                    {
                        bool? nullableBool = e.Value as bool?;
                        if (nullableBool.HasValue)
                        {
                            e.Value = nullableBool.Value ? "是" : "否";
                            e.FormattingApplied = true;
                            return;
                        }
                    }
                    
                    // 处理字符串类型（可能已经是格式化后的值）
                    if (e.Value is string)
                    {
                        // 已经是字符串，不需要格式化
                        e.FormattingApplied = false;
                        return;
                    }
                }
            }
            catch
            {
                // 忽略格式化错误，使用默认显示
                e.FormattingApplied = false;
            }
        }

        /// <summary>
        /// DataGridView数据错误事件处理
        /// </summary>
        private void DgvDrugList_DataError(object? sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略数据错误，避免显示默认错误对话框
            e.ThrowException = false;
        }

        /// <summary>
        /// 选择药品列表中的药品
        /// </summary>
        private void DgvDrugList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvDrugList.SelectedRows.Count > 0)
            {
                var selectedRow = dgvDrugList.SelectedRows[0];
                if (selectedRow.DataBoundItem is DrugDto drug)
                {
                    _selectedDrug = drug;
                    _drugId = drug.DrugId; // 保存药品ID
                    
                    // 更新药品信息显示
                    UpdateDrugInfoDisplay(drug);
                    
                    // 更新下拉框选中项
                    if (cmbDrugName != null)
                    {
                        cmbDrugName.SelectedValue = drug.DrugId;
                    }
                }
            }
        }

        /// <summary>
        /// 根据患者姓名或卡号自动填充患者信息
        /// </summary>
        private async void txtPatientName_Leave(object sender, EventArgs e)
        {
            // 如果患者ID已经保存，不需要自动填充
            if (_patientId.HasValue && _patientId.Value > 0)
                return;

            // 优先通过卡号查找（如果已填写卡号）
            if (!string.IsNullOrWhiteSpace(txtCardNumber?.Text))
            {
                await LoadPatientByCard(txtCardNumber.Text.Trim());
            }
        }

        /// <summary>
        /// 根据卡号加载患者信息
        /// </summary>
        private async Task LoadPatientByCard(string cardNumber)
        {
            try
            {
                var response = await _httpClient.GetAsync($"api/Patient/GetByCard?cardNumber={Uri.EscapeDataString(cardNumber)}");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<Patient>>(json, _jsonOptions);
                    
                    if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                    {
                        var patient = apiResult.Data;
                        // 保存患者ID到私有变量
                        _patientId = patient.PatientId;
                        
                        // 自动填充患者信息显示
                        if (txtPatientName != null)
                            txtPatientName.Text = patient.PatientName ?? "";
                        if (txtCardNumber != null)
                            txtCardNumber.Text = patient.CardNumber ?? "";
                        // 其他信息可以根据需要填充
                    }
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误，不干扰用户输入
                System.Diagnostics.Debug.WriteLine($"根据卡号加载患者信息失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 卡号输入框失去焦点时自动加载患者信息
        /// </summary>
        private async void txtCardNumber_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtCardNumber.Text))
            {
                await LoadPatientByCard(txtCardNumber.Text.Trim());
            }
        }

        /// <summary>
        /// 刷新药品列表
        /// </summary>
        private void RefreshDrugList()
        {
            if (cmbDrugName != null)
            {
                cmbDrugName.DataSource = null;
                cmbDrugName.DisplayMember = "DrugName";
                cmbDrugName.ValueMember = "DrugId";
                cmbDrugName.DataSource = _drugs;
            }
        }

        /// <summary>
        /// 选择药品
        /// </summary>
        private void cmbDrugName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDrugName.SelectedValue != null && int.TryParse(cmbDrugName.SelectedValue.ToString(), out int drugId))
            {
                _selectedDrug = _drugs.Find(d => d.DrugId == drugId);
                if (_selectedDrug != null)
                {
                    _drugId = drugId; // 保存药品ID
                    UpdateDrugInfoDisplay(_selectedDrug);
                }
            }
        }

        /// <summary>
        /// 搜索药品
        /// </summary>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                var drugName = txtSearchDrugName.Text?.Trim();
                var url = $"api/Drug/GetDrugs?drugName={Uri.EscapeDataString(drugName ?? "")}&onlyEnabled=true";

                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _drugs = apiResult.Data;
                    RefreshDrugList();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 药品出库（发药）
        /// </summary>
        private async void btnOutboundDrug_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段 - 使用保存的药品ID
                if (!_drugId.HasValue || _drugId.Value <= 0)
                {
                    MessageBox.Show("请选择要出库的药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(txtQuantity.Text, out int quantity) || quantity <= 0)
                {
                    MessageBox.Show("请输入有效的出库数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (_selectedDrug != null && _selectedDrug.Inventory < quantity)
                {
                    MessageBox.Show($"库存不足，当前库存：{_selectedDrug.Inventory}，需要数量：{quantity}", 
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 使用保存的患者ID（优先使用私有变量，如果没有则尝试从界面获取）
                int patientId = 0;
                if (_patientId.HasValue && _patientId.Value > 0)
                {
                    patientId = _patientId.Value;
                }
                else if (!string.IsNullOrWhiteSpace(txtPatientId?.Text) && int.TryParse(txtPatientId.Text, out int parsedPatientId) && parsedPatientId > 0)
                {
                    patientId = parsedPatientId;
                }
                else if (!string.IsNullOrWhiteSpace(txtPatientName?.Text))
                {
                    // 如果只填写了患者姓名，尝试根据姓名查找患者
                    // 如果找不到，patientId保持为0，后端需要处理这种情况
                    patientId = 0;
                }

                // 获取单价（优先使用选中药品的售价）
                decimal unitPrice = 0;
                if (_selectedDrug != null)
                {
                    unitPrice = _selectedDrug.SellingPrice;
                }
                else if (!string.IsNullOrWhiteSpace(txtUnitPrice?.Text) && decimal.TryParse(txtUnitPrice.Text, out decimal parsedPrice) && parsedPrice > 0)
                {
                    unitPrice = parsedPrice;
                }
                else
                {
                    MessageBox.Show("无法获取药品单价，请重新选择药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 使用保存的ID创建命令
                var command = new OutboundDrugCommand
                {
                    DrugId = _drugId.Value,
                    PrescriptionItemId = _prescriptionItemId,
                    AppointmentId = _appointmentId,
                    PatientId = patientId,
                    CardNumber = txtCardNumber?.Text?.Trim(),
                    RegistrationNum = txtRegistrationNum?.Text?.Trim(),
                    PatientName = txtPatientName?.Text?.Trim(),
                    Quantity = quantity,
                    UnitPrice = unitPrice,
                    Operator = "系统操作员", // 这里可以从登录信息获取
                    Remarks = txtRemarks?.Text?.Trim()
                };

                // 如果是从检药单发药，确保关联处方明细ID
                if (_inspectionInfo != null && !command.PrescriptionItemId.HasValue)
                {
                    command.PrescriptionItemId = _inspectionInfo.PrescriptionItemId;
                    _prescriptionItemId = _inspectionInfo.PrescriptionItemId;
                }

                var json = JsonSerializer.Serialize(command);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("api/Drug/OutboundDrug", content);
                response.EnsureSuccessStatusCode();
                var responseJson = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(responseJson, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功)
                {
                    MessageBox.Show("药品出库成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    LoadAllDrugs(); // 重新加载药品列表以更新库存
                    RefreshDrugListGridView(); // 刷新列表显示
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "出库失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"药品出库失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清除搜索条件
        /// </summary>
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtSearchDrugName.Text = "";
            LoadAllDrugs();
        }

        /// <summary>
        /// 数量输入框变化事件
        /// </summary>
        private void TxtQuantity_TextChanged(object? sender, EventArgs e)
        {
            CalculateTotalAmount();
        }
        
        /// <summary>
        /// 单价输入框变化事件
        /// </summary>
        private void TxtUnitPrice_TextChanged(object? sender, EventArgs e)
        {
            CalculateTotalAmount();
        }
        
        /// <summary>
        /// 计算总金额（数量 × 单价）
        /// </summary>
        private void CalculateTotalAmount()
        {
            if (lblTotalAmount == null) return;
            
            try
            {
                int quantity = 0;
                decimal unitPrice = 0;
                
                if (!string.IsNullOrWhiteSpace(txtQuantity?.Text) && int.TryParse(txtQuantity.Text, out int qty))
                {
                    quantity = qty;
                }
                
                if (!string.IsNullOrWhiteSpace(txtUnitPrice?.Text) && decimal.TryParse(txtUnitPrice.Text, out decimal price))
                {
                    unitPrice = price;
                }
                
                decimal totalAmount = quantity * unitPrice;
                lblTotalAmount.Text = $"总金额：{totalAmount:F2} 元";
            }
            catch
            {
                lblTotalAmount.Text = "总金额：0.00 元";
            }
        }
        
        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            // 清空ID变量
            _patientId = null;
            _prescriptionItemId = null;
            _appointmentId = null;
            _drugId = null;
            
            // 清空界面显示
            if (txtCurrentInventory != null) txtCurrentInventory.Text = "";
            if (txtQuantity != null) txtQuantity.Text = "";
            if (txtUnitPrice != null) txtUnitPrice.Text = "";
            if (txtCardNumber != null) txtCardNumber.Text = "";
            if (txtRegistrationNum != null) txtRegistrationNum.Text = "";
            if (txtPatientName != null) txtPatientName.Text = "";
            if (txtRemarks != null) txtRemarks.Text = "";
            
            // 清空显示标签
            if (lblPatientInfo != null) lblPatientInfo.Text = "患者信息：";
            if (lblDrugInfo != null) lblDrugInfo.Text = "药品信息：请选择药品";
            if (lblTotalAmount != null) lblTotalAmount.Text = "总金额：0.00 元";
            
            // 清空隐藏的ID输入框（如果存在）
            if (txtPatientId != null) txtPatientId.Text = "";
            if (txtPrescriptionItemId != null) txtPrescriptionItemId.Text = "";
            if (txtAppointmentId != null) txtAppointmentId.Text = "";
            if (txtDrugId != null) txtDrugId.Text = "";
            
            _selectedDrug = null;
            _inspectionInfo = null;
        }
    }
}

